package com.jm.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jm.common.util.entity.R;
import com.jm.common.util.entity.SelectCondition;
import com.jm.pojo.Admin;
import com.jm.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    /**
     * 管理员登录
     */
    @PostMapping("/login")
    public R<Admin> login(@RequestBody SelectCondition condition, HttpServletRequest request) {
        String username = condition.getUsername();
        String password = condition.getPassword();
//       根据用户名密码取得管理员对象
        Admin admin = adminService.getLogin(username, password);
        if (admin == null) {
//            登陆失败
            return R.error("找不到对应的用户,请检查你的身份或者用户名与密码");
        }
//            登陆成功
        request.getSession().setAttribute("admin", admin.getId());
        return R.success(admin);
    }

    /**
     * 管理员登出
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        request.getSession().removeAttribute("admin");
        return R.success("退出成功");
    }

    /**
     * 条件分页查询
     */
    @GetMapping("/page")
    public R<IPage<Admin>> selectByPageCondition(SelectCondition condition) {
        IPage<Admin> admins = adminService.selectByPageCondition(condition);
        return R.success(admins);
    }

    /**
     * 添加管理员
     */
    @PostMapping()
    public R<String> addAdmin(@RequestBody Admin admin) {
        String username = admin.getUsername();
//        判断用户名是否已经存在
        boolean result = adminService.checkUsernameIsExists(username);
        if (result) return R.error("用户名" + username + "已经存在,请更换一个用户名");
//        若这个用户名不存在则进行添加操作
        admin.setPassword("123456");
        boolean save = adminService.save(admin);
        if (save) return R.success("添加成功");
        return R.error("添加失败");
    }

    /**
     * 根据id查询
     */
    @GetMapping("/{id}")
    public R<Admin> getById(@PathVariable String id) {
        Admin admin = adminService.getById(id);
        if (admin == null) return R.error("根据id未获得该用户信息");
        return R.success(admin);
    }

    @PutMapping
    public R<String> update(@RequestBody Admin admin) {
        boolean result = adminService.updateById(admin);
        if (result) return R.success("修改成功");
        return R.error("添加失败");
    }
}
